package com.ss.android.article.base.app;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.bytedance.article.common.c.TTUtils;
import com.bytedance.common.utility.Logger;
import com.bytedance.common.utility.c.SharedPreferenceCompat;
import com.bytedance.frameworks.baselib.network.dispatcher.IRequest.Priority;
import com.bytedance.ttnet.a.AppConfig;
import com.ss.android.common.util.NetworkUtils;
import com.ss.android.common.util.ToolUtils;
import com.ss.android.newmedia.MediaAppData;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

public final class JsConfigHelper {
    class a implements d {
        public final JsConfigHelper mJsConfigHelper;
        public int a;
        public String jsResDir;
        public String jsDataFileName;
        String jsDataPath;
        protected String KEY_ZIP_JS_VERSION;
        protected String KEY_ZIP_JS_MD5;
        protected String KEY_ZIP_JS_URL;
        protected String KEY_SAVED_ZIP_JS_VERSION;
        protected String KEY_SAVED_ZIP_JS_MD5;
        protected String KEY_ASSET_JS_VERSION;
        protected String savedZipJsMd5;
        int assetJsVersion;
        File m;
        boolean n;
        private String jsDataDir;
        private int zipJsVersion;
        private String zipJsMd5;
        private String zipJsUrl;
        private int savedZipJsVersion;
        private File u;
        private boolean v;
        private long w;
        private long x;
        private long y;

        public a(JsConfigHelper jsConfigHelper, int arg7) {
            this.mJsConfigHelper = jsConfigHelper;
            this.a = 5700;
            this.jsResDir = "ss_js_res";
            this.jsDataFileName = "android.js.dat";
            this.jsDataDir = "asset";
            this.jsDataPath = "file:///android_asset/android.js.dat";
            this.KEY_ZIP_JS_VERSION = "zip_js_version";
            this.KEY_ZIP_JS_MD5 = "zip_js_md5";
            this.KEY_ZIP_JS_URL = "zip_js_url";
            this.KEY_SAVED_ZIP_JS_VERSION = "saved_zip_js_version";
            this.KEY_SAVED_ZIP_JS_MD5 = "saved_zip_js_md5";
            this.KEY_ASSET_JS_VERSION = "asset_js_version";
            this.u = null;
            this.v = false;
            this.w = 0;
            this.x = 0;
            this.y = 0;
            this.m = null;
            this.n = false;
            this.a = arg7;
            try {
                this.m = new File(new File(jsConfigHelper.mContext.getFilesDir(), this.jsResDir), this.jsDataDir);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }

        public void a() {
            if (this.i()) {
                try {
                    if (!this.n) {
                        int updateVersionCode = this.mJsConfigHelper.mAppData.getAppContext().getUpdateVersionCode();
                        if (this.assetJsVersion < updateVersionCode || (!this.isLocalAssetsExists(this.m))) {
                            this.n = true;
                            com.bytedance.common.utility.b.a.a(new p(this, updateVersionCode), new Void[0]);
                        }
                    }
                } catch (Throwable throwable) {

                }
            }

            if (!this.v && !android.support.design.a.isTextEmpty(this.zipJsMd5) && !android.support.design.a.isTextEmpty(this.zipJsUrl)) {
                long ts = System.currentTimeMillis();
                if (ts - this.w >= 900000L) {
                    if (TTUtils.isValidUrl(this.zipJsUrl)
                            && !NetworkUtils.isNetworkAvailable(this.mJsConfigHelper.mContext)) {
                        return;
                    }
                    this.v = true;
                    this.w = ts;
                    com.bytedance.common.utility.b.a.a(new JsConfigHelper.o$b(
                                    this.mJsConfigHelper,
                                    this,
                                    this.zipJsVersion,
                                    this.zipJsMd5,
                                    this.zipJsUrl,
                                    this.savedZipJsVersion,
                                    this.savedZipJsMd5),
                            new Void[0]);
                }
            }
        }

        public boolean isLocalAssetsExists(File file) {
            File jsFile = new File(file, "v55/js/android.js");
            if ((jsFile.isFile()) && jsFile.length() > 0L) {
                File libJsFile = new File(file, "v55/js/lib.js");
                if ((libJsFile.isFile()) && libJsFile.length() > 0L) {
                    File cssFile = new File(file, "v55/css/android.css");
                    if ((cssFile.isFile()) && cssFile.length() > 0L) {
                        return true;
                    }
                }
            }
            return false;
        }

        public final void intoSp(SharedPreferences.Editor editor) {
            editor.putInt(this.KEY_ZIP_JS_VERSION, this.zipJsVersion);
            editor.putString(this.KEY_ZIP_JS_MD5, this.zipJsMd5);
            editor.putString(this.KEY_ZIP_JS_URL, this.zipJsUrl);
            editor.putInt(this.KEY_ASSET_JS_VERSION, this.assetJsVersion);
        }

        public final void loadFromSp(SharedPreferences sharedPreferences) {
            this.zipJsVersion = sharedPreferences.getInt(this.KEY_ZIP_JS_VERSION, 0);
            this.zipJsMd5 = sharedPreferences.getString(this.KEY_ZIP_JS_MD5, "");
            this.zipJsUrl = sharedPreferences.getString(this.KEY_ZIP_JS_URL, "");
            this.savedZipJsVersion = sharedPreferences.getInt(this.KEY_SAVED_ZIP_JS_VERSION, 0);
            this.savedZipJsMd5 = sharedPreferences.getString(this.KEY_SAVED_ZIP_JS_MD5, "");
            this.assetJsVersion = sharedPreferences.getInt(this.KEY_ASSET_JS_VERSION, 0);
        }

        public void a(Boolean arg7,
                      boolean arg8,
                      int savedZipJsVersion,
                      String savedZipJsMd5) {
            this.v = false;
            boolean v2 = arg7 != null ? arg7.booleanValue() : false;
            boolean v0 = !v2 && arg8;
            Logger.i("AppData", "fetch js result: " + v2 + " " + v0 + " " + this.zipJsVersion + " " + this.savedZipJsVersion);
            if (v2) {
                if (savedZipJsVersion == this.savedZipJsVersion && (savedZipJsMd5.equals(this.savedZipJsMd5))) {
                    return;
                }
                this.savedZipJsVersion = savedZipJsVersion;
                this.savedZipJsMd5 = savedZipJsMd5;
            }

            if (v0) {
                this.savedZipJsVersion = 0;
                this.savedZipJsMd5 = null;
            }

            try {
                SharedPreferences.Editor editor = MediaAppData.getSharedPreference(this.mJsConfigHelper.mContext).edit();
                editor.putInt(this.KEY_SAVED_ZIP_JS_VERSION, this.savedZipJsVersion);
                editor.putString(this.KEY_SAVED_ZIP_JS_MD5, this.savedZipJsMd5);
                SharedPreferenceCompat.commit(editor);
            } catch (Exception exception) {
            }
        }

        public final boolean a(File file, File arg3) throws Exception {
            try {
                com.bytedance.article.b.a.q.a().a(file, arg3);
                return this.isLocalAssetsExists(arg3);
            } catch (Exception exception) {
                exception.printStackTrace();
                return false;
            }
        }

        public final boolean a(JSONObject arg6) {
            boolean v0_1;
            boolean v2_1;
            int v0 = 0;
            int v1 = 1;
            if (!this.mJsConfigHelper.mAppData.getAbSettings().isUpdateJs()) {
                int v2 = arg6.optInt(this.KEY_ZIP_JS_VERSION, 0);
                if (v2 <= 0 || v2 == this.zipJsVersion) {
                    v2_1 = false;
                } else {
                    this.zipJsVersion = v2;
                    v0 = 1;
                    v2_1 = true;
                }

                String v3 = arg6.optString(this.KEY_ZIP_JS_MD5, "");
                if (v3 != null) {
                    v3 = v3.toLowerCase(Locale.getDefault());
                }

                if (!android.support.design.a.isTextEquals(this.zipJsMd5, v3)) {
                    this.zipJsMd5 = v3;
                    v0 = 1;
                    v2_1 = true;
                }

                v3 = arg6.optString(this.KEY_ZIP_JS_URL, "");
                if (!android.support.design.a.isTextEquals(this.zipJsUrl, v3)) {
                    this.zipJsUrl = v3;
                    v0_1 = true;
                } else {
                    v1 = v0;
                    v0_1 = v2_1;
                }

                if (v1 != 0) {
                    this.w = 0;
                }

                if (!v0_1) {
                    return v0_1;
                }

                this.a();
            } else {
                v0_1 = this.b(arg6);
            }

            return v0_1;
        }

        private boolean b(JSONObject arg8) {
            boolean v0 = false;
            String feArticleAssets = arg8.optString("fe_article_assets", this.h());
            if (!android.support.design.a.isTextEquals(this.zipJsUrl, feArticleAssets)) {
                int zipJsVersion = -1;
                String zipJsMd5 = null;
                if (!TextUtils.isEmpty(feArticleAssets)) {
                    try {
                        String[] v3_1 = feArticleAssets.substring(
                                feArticleAssets.lastIndexOf("/") + 1,
                                feArticleAssets.lastIndexOf("."))
                                .split("_");
                        if (v3_1.length >= 3) {
                            zipJsVersion = Integer.parseInt(v3_1[1]);
                            zipJsMd5 = v3_1[2];
                        }
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                }

                this.zipJsUrl = feArticleAssets;
                if (zipJsVersion < 0) {
                    zipJsVersion = this.getZipJsVersion();
                }

                this.zipJsVersion = zipJsVersion;
                if (zipJsMd5 == null) {
                    zipJsMd5 = this.getZipJsMd5();
                }

                this.zipJsMd5 = zipJsMd5;
                this.w = 0;
                this.a();
                v0 = true;
            }

            return v0;
        }

        public final String b() {
            return this.jsDataFileName;
        }

        public final String c() {
            return this.jsResDir;
        }

        public String d() {
            String v0;
            if (this.a >= this.savedZipJsVersion) {
                v0 = this.m.getAbsolutePath();
                return v0;
            }

            if (this.a >= this.zipJsVersion) {
                return this.m.getAbsolutePath();
            }

            long v0_1 = System.currentTimeMillis();
            try {
                if (this.u == null || android.support.design.a.d(this.u.getName(), -1) != this.savedZipJsVersion) {
                    this.u = new File(new File(this.mJsConfigHelper.mContext.getFilesDir(), this.jsResDir), String.valueOf(this.savedZipJsVersion));
                }

                if (v0_1 - this.x > 20000) {
                    this.x = v0_1;
                    if (!this.u.exists()) {
                        return this.m.getAbsolutePath();
                    }
                }

                if (v0_1 - this.y > 60000) {
                    this.y = v0_1;
                    if (!this.isLocalAssetsExists(this.u)) {
                        return this.m.getAbsolutePath();
                    }
                }

                v0 = this.u.getAbsolutePath();
            } catch (Exception v0_2) {
                v0 = this.m.getAbsolutePath();
            }

            return v0;
        }

        public String e() {
            return null;
        }

        protected int getZipJsVersion() {
            return -1;
        }

        protected String getZipJsMd5() {
            return null;
        }

        protected String h() {
            return null;
        }

        protected boolean i() {
            return true;
        }
    }

    final class o$b extends AsyncTask {
        private final JsConfigHelper h;
        private d a;
        private int b;
        private String c;
        private String d;
        private int e;
        private String f;
        private boolean g;

        public o$b(JsConfigHelper arg2, d arg3, int arg4, String arg5, String arg6, int arg7, String arg8) {
            this.h = arg2;
            this.g = false;
            this.a = arg3;
            this.b = arg4;
            this.c = arg5;
            this.d = arg6;
            this.e = arg7;
            this.f = arg8;
        }

        private Boolean fetchJs() {
            int v1_2;
            String v1_1;
            File v12;
            File v2;
            Boolean v0 = null;
            if (this.b <= 0 || (android.support.design.a.isTextEmpty(this.c)) || (android.support.design.a.isTextEmpty(this.d))) {
                v0 = Boolean.valueOf(false);
            } else if (!NetworkUtils.isNetworkAvailable(this.h.mContext)) {
                v0 = Boolean.valueOf(false);
            } else {
                try {
                    Logger.d("JsConfigHelper", "try fetch js:" + this.b + " " + this.e);
                    v2 = new File(this.h.mContext.getFilesDir(), this.a.c());
                    if (!v2.exists()) {
                        v2.mkdirs();
                    }

                    if (!v2.isDirectory()) {
                        Logger.w("JsConfigHelper", "js dir not exists");
                        return Boolean.valueOf(false);
                    }

                    v12 = new File(v2, this.a.b());
                    File v13 = new File(v2, String.valueOf(this.b));
                    if (this.e != this.b) {
                        v1_1 = com.bytedance.common.utility.aa.a(v12);
                        if (v1_1 == null) {
                        } else if (!v1_1.equals(this.c)) {
                        } else {
                            v0 = null;
                        }
                    } else {
                        v1_1 = com.bytedance.common.utility.aa.a(v12);
                        if (v1_1 != null && (v1_1.equals(this.f))) {
                            v0 = null;
                        }
                        if (v0 != null) {
                        } else if (!v13.isDirectory()) {
                        } else if (!this.a.isLocalAssetsExists(v13)) {
                        } else {
                            File[] v3 = v2.listFiles();
                            int v4 = v3.length;
                            v1_2 = 0;
                            while (true) {
                                if (v1_2 >= v4) {
                                    return Boolean.valueOf(true);
                                }

                                File v5 = v3[v1_2];
                                int v6 = android.support.design.a.d(v5.getName(), 0);
                                if (v6 > 0 && v6 != this.b && (v5.isDirectory())) {
                                    ToolUtils.c(v5.getAbsolutePath());
                                    v5.delete();
                                }
                                ++v1_2;
                                continue;
                            }
                        }
                        this.g = true;
                    }
                    if (v0 != null) {
                        if (!NetworkUtils.downloadFile(1048576, this.d, v2.getAbsolutePath(), null, this.a.b(), null, null, null, null, null, null)) {
                            return Boolean.valueOf(false);
                        } else if (!v12.isFile()) {
                            return Boolean.valueOf(false);
                        } else if (!this.c.equals(com.bytedance.common.utility.aa.a(v12))) {
                            return Boolean.valueOf(false);
                        }
                    }

                    if (!this.a.a(v12, v13)) {
                        return Boolean.valueOf(false);
                    }

                    if (this.a.isLocalAssetsExists(v13)) {
                        return Boolean.valueOf(true);
                    }
                    Logger.w("AppData", "validate js version failed");
                } catch (Exception e) {
                    Logger.w("AppData", "fetch js exception: " + e);
                }

                v0 = Boolean.valueOf(false);
            }

            return v0;
        }

        protected final Object doInBackground(Object[] arg2) {
            return this.fetchJs();
        }

        protected final void onPostExecute(Object arg5) {
            this.a.a(((Boolean) arg5), this.g, this.b, this.c);
        }
    }

    final class c extends a {
        private final JsConfigHelper s;
        public String p;
        public String q;
        public AtomicBoolean r;

        public c(JsConfigHelper arg4) {
            super(arg4, -1);
            this.s = arg4;
            this.p = null;
            this.q = null;
            this.r = new AtomicBoolean(false);
            this.a = -1;
            this.jsResDir = "ss_hijack_res";
            this.jsDataFileName = "detect.js.dat";
            this.KEY_ZIP_JS_VERSION = "hijack_js_version";
            this.KEY_ZIP_JS_MD5 = "hijack_js_md5";
            this.KEY_ZIP_JS_URL = "hijack_js_url";
            this.KEY_SAVED_ZIP_JS_VERSION = "saved_hijack_js_version";
            this.KEY_SAVED_ZIP_JS_MD5 = "saved_hijack_js_md5";
        }

        public final void a() {
            if (AppConfig.getInstance(this.s.mContext).l()) {
                super.a();
                this.j();
            }
        }

        public final void a(Boolean arg1, boolean arg2, int arg3, String arg4) {
            super.a(arg1, arg2, arg3, arg4);
            this.j();
        }

        public final boolean isLocalAssetsExists(File file) {
            File v0 = new File(file, "detect.js");
            boolean v0_1 = !v0.isFile() || v0.length() <= 0 ? false : true;
            return v0_1;
        }

        public final String d() {
            String v0 = super.d();
            if (!android.support.design.a.isTextEmpty(v0)) {
                File v0_1 = new File(new File(v0), "detect.js");
                if (v0_1.exists()) {
                    v0 = v0_1.getAbsolutePath();
                } else {
                    return null;
                }
            } else {
                v0 = null;
            }

            return v0;
        }

        public final String e() {
            String v0 = !AppConfig.getInstance(this.s.mContext).l() ? null : this.p;
            return v0;
        }

        protected final int getZipJsVersion() {
            return 103;
        }

        protected final String getZipJsMd5() {
            return "45e603126faf059eb95592f74625768e";
        }

        protected final String h() {
            return "http://s0.pstatp.com/site/download/app/js/103/detect.js.dat";
        }

        protected final boolean i() {
            return false;
        }

        private void j() {
            if (!this.r.get()) {
                try {
                    if (!android.support.design.a.isTextEmpty(this.p) && !android.support.design.a.isTextEmpty(this.q) && (this.q.equals(this.savedZipJsMd5))) {
                        return;
                    }

                    String v0_1 = this.d();
                    if (android.support.design.a.isTextEmpty(v0_1)) {
                        return;
                    }
                    this.r.getAndSet(true);
                    new LoadHijackJsThread(this, "LoadHijackJsThread", Priority.NORMAL, v0_1).start();
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                }
            }
        }
    }

    interface d {
        void intoSp(SharedPreferences.Editor editor);

        void loadFromSp(SharedPreferences sharedPreferences);

        boolean a(JSONObject arg1);

        void a();

        void a(Boolean arg1, boolean arg2, int arg3, String arg4);

        boolean isLocalAssetsExists(File file);

        boolean a(File arg1, File arg2) throws Exception;

        String b();

        String c();

        String d();

        String e();
    }

    Context mContext;
    AppData mAppData;
    Map c;

    public JsConfigHelper(Context context, AppData appData) {
        int updateVersionCode;
        this.c = new LinkedHashMap();
        this.mContext = context.getApplicationContext();
        this.mAppData = appData;
        if (!this.mAppData.getAbSettings().isUpdateJs()) {
            updateVersionCode = this.mAppData.getAppContext().getUpdateVersionCode();
        } else {
            try {
                updateVersionCode = android.support.design.a.d(context, "JS_VERSION_CODE");
            } catch (Exception exception) {
                updateVersionCode = 0;
            }
        }
        this.c.put(Integer.valueOf(0), new a(this, updateVersionCode));
        this.c.put(Integer.valueOf(1), new c(this));
    }

    final void a() {
        if (this.c != null) {
            Iterator<Map.Entry> v1 = this.c.entrySet().iterator();
            while (v1.hasNext()) {
                Object v0 = v1.next().getValue();
                if (v0 == null) {
                    continue;
                }
                ((d) v0).a();
            }
        }
    }

    public final boolean copyJsData(String jsDataPath, String outputDirStr, String outputFileName) {
        File outputDir;
        InputStream is = null;
        if (android.support.design.a.isTextEmpty(jsDataPath)) {
            return false;
        }

        if (android.support.design.a.isTextEmpty(outputDirStr)) {
            return false;
        }

        if (android.support.design.a.isTextEmpty(outputFileName)) {
            return false;
        }
        FileOutputStream fos = null;
        try {
            is = this.mContext.getAssets().open(jsDataPath.substring(22));
            outputDir = new File(outputDirStr);
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }
            fos = new FileOutputStream(new File(outputDir, outputFileName));
            byte[] buf = new byte[4096];
            while (true) {
                int len = is.read(buf);
                if (len <= 0) {
                    break;
                }

                fos.write(buf, 0, len);
            }
            fos.flush();
            return true;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return false;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {

                }
            }

            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {

                }
            }
        }
    }
}

